#include "stdafx.h"
#include "C3DOjbect.h"
#include <fstream>
#include <stdio.h>
using namespace std;

#define BUFFER_OFFSET(i) ((char *)NULL+(i))


C3DOjbect::C3DOjbect(void)
{
	fAlpha = 1;
}

C3DOjbect::~C3DOjbect(void)
{
}

void C3DOjbect::LoadObject(char * strObjFile, char * strMtlFile)
{
	mtlLoader.loadMtl(strMtlFile, &mtl, &textures);
	objLoader.loadObj(strObjFile, &mtl, &model);
}

void C3DOjbect::DrawObject()
{
	GLuint current_texID = 99;

	glPushMatrix();
	{
		int o = 0;

		while( o != model.object.size() )
		{
			float r, g, b;
			int i = 0;

			cObjObject & object = model.object[o];

			while (i != object.face.size()) {
				{
					int mn = object.face[i].material;
					r = mtl[ mn ].Kd[0];
					g = mtl[ mn ].Kd[1];
					b = mtl[ mn ].Kd[2];
					glColor3f( r, g, b );

					if( mtl[mn].bKdTexture == true )
					{
						if ( current_texID != mtl[mn].map_Kd_texture_ID )
						{
							current_texID = mtl[mn].map_Kd_texture_ID;

							glBindTexture(GL_TEXTURE_2D, mtl[mn].map_Kd_texture_ID);

							glEnable(GL_TEXTURE_2D);
							glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
							glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
						}
					}
					else
					{
						current_texID = 0;

						glBindTexture(GL_TEXTURE_2D, 0);
					}


					glBegin(GL_TRIANGLE_FAN);

					for (std::vector<int>::size_type j = 0; j != object.face[i].vertex.size(); ++j) {

						if( object.face[i].normal.size() > 0 )
						{
							int normalindex  = object.face[i].normal[j];
							glNormal3f(model.normal[normalindex-1].x,
								model.normal[normalindex-1].y,
								model.normal[normalindex-1].z);
						}

						if( object.face[i].texCoord.size() > 0 )
						{
							int texcoordindex  = object.face[i].texCoord[j];
							glTexCoord2f(model.texCoord[texcoordindex-1].u,
								model.texCoord[texcoordindex-1].v);
						}

						int vertexindex = object.face[i].vertex[j];
						glVertex3f(model.vertex[vertexindex-1].x,
							model.vertex[vertexindex-1].y,
							model.vertex[vertexindex-1].z);
					}

					glEnd();
				}

				i++;
			}

			o++;
		}
	}
	glPopMatrix();
}